//
//  CardDallocTableViewController.m
//  LoveAttention
//
//  Created by 鞠超 on 15/12/31.
//  Copyright © 2015年 JC. All rights reserved.
//


#import "CardDallocTableViewController.h"
#import "CardDallocTableViewCell.h"
#import "CardDetialViewController.h"
#import "model_CardDalloc.h"

#import "MJRefresh.h"
#import "DataProvider.h"
#import "SVProgressHUD.h"
#import "UIImageView+WebCache.h"

#define DEFAULT_VOID_COLOR [UIColor whiteColor]
@interface CardDallocTableViewController () <UITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray * arr_data;


@property (nonatomic, strong) UITextField * text_search;

@end

@implementation CardDallocTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self p_navigationController];
    
    [self p_setupView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidAppear:(BOOL)animated
{
    
}

#pragma mark - navigationController
- (void)p_navigationController
{
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    self.navigationItem.title = @"卡券核销";
    UIButton * btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [btn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
        btn.frame = CGRectMake(10, 20, 25, 30);
    [btn addTarget:self action:@selector(leftBarButtonItemAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
}
//点击事件(左)
- (void)leftBarButtonItemAction:(UIBarButtonItem *)bar
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 布局
- (void)p_setupView
{
    //注册
    [self.tableView registerClass:[CardDallocTableViewCell class] forCellReuseIdentifier:@"cell_CardDalloc"];
    
    
    UIView * view_search = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    view_search.backgroundColor = [UIColor whiteColor];
    
    UIImageView * image_search = [[UIImageView alloc] initWithFrame:CGRectMake(15, 10, 30, 30)];
    image_search.image = [UIImage imageNamed:@"iconfont-sousuo"];
    [view_search addSubview:image_search];
    
    self.text_search = [[UITextField alloc] init];
    
    self.text_search.returnKeyType = UIReturnKeyDone;
    self.text_search.frame = CGRectMake(CGRectGetMaxX(image_search.frame) + 10, 7, self.view.frame.size.width - CGRectGetMaxX(image_search.frame) - 70, 36);
    UIView * view_w = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 2)];
    self.text_search.leftView = view_w;
    self.text_search.leftViewMode = UITextFieldViewModeAlways;
    self.text_search.layer.cornerRadius = 5;
    self.text_search.layer.borderColor = [UIColor grayColor].CGColor;
    self.text_search.layer.borderWidth = 1;
    self.text_search.keyboardType = UIKeyboardTypeNumberPad;
    self.text_search.clearButtonMode = UITextFieldViewModeAlways;
//    self.text_search.layer.cornerRadius = 5;
//    self.text_search.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
//    self.text_search.layer.borderWidth = 1;
    self.text_search.delegate = self;
    [view_search addSubview:self.text_search];
    
    UIButton * btn_search = [UIButton buttonWithType:(UIButtonTypeSystem)];
    btn_search.frame = CGRectMake(CGRectGetMaxX(self.text_search.frame) + 5, 10, 50, 30);
//    btn_search.backgroundColor = [UIColor orangeColor];
//    [btn_search setBackgroundImage:[UIImage imageNamed:@"iconfont-quxiao"] forState:(UIControlStateNormal)];
    [btn_search setTitle:@"搜索" forState:(UIControlStateNormal)];
    [btn_search setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [view_search addSubview:btn_search];
    [btn_search addTarget:self action:@selector(btn_searchAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.tableView.tableHeaderView = view_search;
    
    self.tableView.tableFooterView = [[UIView alloc] init];
}

#pragma mark - textFiled;
- (void)btn_searchAction:(UIButton *)sender
{
    [self.text_search resignFirstResponder];
    
    if([self.text_search.text length] == 0)
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"搜索内容不能为空" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"知道了" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:action];
    }
    else
    {
        [self p_data];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.text_search resignFirstResponder];
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.text_search resignFirstResponder];

    if([textField.text length] == 0)
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"搜索内容不能为空" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"知道了" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:action];
    }
    else
    {
        [self p_data];
    }
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr_data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    model_CardDalloc * model = self.arr_data[indexPath.row];
    
    CardDallocTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_CardDalloc" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
//加数据
    NSString *url = [NSString stringWithFormat:@"%@upload/%@",Url,model.couponimage];
    cell.image.layer.masksToBounds = YES;
    [cell.image sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"头像"]];
    cell.detail.text = model.couponname;
    cell.name.text = model.uname;
    
    cell.view_color.backgroundColor = [self colorWithHexString:model.couponcolor];
    
    switch ([model.state intValue]) {
        case -1:
            cell.status.text = @"待领取";
            break;
        case 0:
            cell.status.text = @"未使用";
            break;
        case 1:
            cell.status.text = @"赠送中";
            break;
        case 2:
            cell.status.text = @"已使用";
            break;
        case 3:
            cell.status.text = @"已过期";
            break;
            
        default:
            break;
    }
    
    return cell;
}

- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 160;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(self.arr_data.count != 0)
    {
        model_CardDalloc * model = self.arr_data.firstObject;
        
        CardDetialViewController * cardDallocViewController = [[CardDetialViewController alloc] init];
        
        cardDallocViewController.couponid = model.couponid;
        
        [self showViewController:cardDallocViewController sender:nil];
    }
}

////删除cell
//
//- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return @"删除";
//}
//
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return YES;
//}
//
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return UITableViewCellEditingStyleDelete;
//}
//
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    //做删除操作，并调接口删除后台数据
//}

#pragma mark - 数据
- (void)p_data
{
    DataProvider * dataprovider = [[DataProvider alloc] init];
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    
    [dataprovider setDelegateObject:self setBackFunctionName:@"CardDalloc:"];
    
    [dataprovider couponSearchWithMerchantid:[defaults objectForKey:@"merchantid"] couponnum:self.text_search.text];
}

- (void)CardDalloc:(id )dict
{
    NSLog(@"%@",dict);
    
    self.arr_data = nil;

    if ([dict[@"status"][@"succeed"] intValue] == 1) {
        @try
        {
            NSDictionary * dic = dict[@"data"];
            
            model_CardDalloc * model = [[model_CardDalloc alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.arr_data addObject:model];
        }
        @catch (NSException *exception) {
            
        }
        @finally {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //刷新tableView(记住,要更新放在主线程中)
                
                [self.tableView reloadData];
            });
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //刷新tableView(记住,要更新放在主线程中)
            
            [self.tableView reloadData];
        });
    }
}


#pragma mark - 懒加载
- (NSMutableArray *)arr_data
{
    if(_arr_data == nil)
    {
        self.arr_data = [NSMutableArray array];
    }
    
    return _arr_data;
}


#pragma mark - 颜色的处理
- (UIColor *)colorWithHexString:(NSString *)stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    
    if ([cString length] < 6)
        return DEFAULT_VOID_COLOR;
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return DEFAULT_VOID_COLOR;
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}




@end
